<?php
	/**
	* admiao
	*/
	class Message_MiiModel 
	{
		
		// function __construct(argument)
		// {
			
		// }
		public function bookMessage($orderid,$openid,$token,$formid,$order_details,$templateid){
			$de = @json_decode($order_details,true);
			$uname = $de['uname'];
			$servicename = $de['goodsname'];
			$booktime = date('Y-m-d H:i',$de['starttime']).'-'.date('H:i',$de['endtime']);
			$url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$token;

			$postdata = '{
			  "touser": "'.$openid.'",  
			  "template_id": "'.$templateid.'", 
			  "page": "mii_ang/pages/personal/index",          
			  "form_id": "'.$formid.'",         
			  "data": {
			      "keyword1": {
			          "value": "'.$uname.'", 
			          "color": "#173177"
			      }, 
			      "keyword2": {
			          "value": "'.$servicename.'", 
			          "color": "#173177"
			      }, 
			      "keyword3": {
			          "value": "'.$booktime.'", 
			          "color": "#173177"
			      } , 
			      "keyword4": {
			          "value": "'.$orderid.'", 
			          "color": "#173177"
			      } , 
			      "keyword5": {
			          "value": "'.$address.'", 
			          "color": "#173177"
			      },
			      "keyword6": {
			          "value": "您的预约订单号为 '.$orderid.' 请在 '.date('Y-m-d H:i',$de['starttime']).' 之前到达本店。", 
			          "color": "#173177"
			      } 		        
			  }
			}'; 
			load()->func('communication');		
			$res = ihttp_post($url,$postdata);
			$code = json_decode($res['content'],true);
			return $code;
		}
	public function sendTplmessage($touser,$token,$template_id, $postdata, $page = '',$form_id) {
		if(empty($touser)) {
			return error(-1, '参数错误,粉丝openid不能为空');
		}
		if(empty($template_id)) {
			return error(-1, '参数错误,模板标示不能为空');
		}
		if(empty($postdata) || !is_array($postdata)) {
			return error(-1, '参数错误,请根据模板规则完善消息内容');
		}
		load()->func('communication');			
		$data = array();
		$data['touser'] = $touser;
		$data['template_id'] = trim($template_id);
		$data['page'] = trim($page);
		$data['form_id'] = trim($form_id);
		$data['data'] = $postdata;
		$data = json_encode($data);
		$post_url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$token}";
		$response = ihttp_request($post_url, $data);
		if(is_error($response)) {
			return error(-1, "访问公众平台接口失败, 错误: {$response['message']}");
		}
		$result = @json_decode($response['content'], true);	
		if(empty($result)) {
			return error(-1, "接口调用失败, 元数据: {$response['meta']}");
		} elseif(!empty($result['errcode'])) {
			return error(-1, "访问微信接口错误, 错误代码: {$result['errcode']}, 错误信息: {$result['errmsg']}");
		}
		return true;
	}		
		//管理消息通知
		public function admin_msg($openid,$order_details,$token){
			$d = array();
			$d = $order_details;
			$uname = $d['uname'];
			$phone = $d['phone'];
			$bookname = $d['goodsname'];
			$booktime =date('Y/m/d H:i',$d['starttime']).'-'.date('H:i',$d['endtime']);
			$address = $d['address'];
			$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$token;	
			$postdata = '{
			    "touser":"'.$openid.'",
			    "msgtype":"text",
			    "text":
			    {
			         "content":"顾客:'.$uname.'\n联系电话:'.$phone.'\n预约项目:'.$bookname.'\n预约时段:'.$booktime.'\n预约技师:'.$d['techname'].'\n联系地址:'.$address.'\n请您及时处理"
			    }
			}';
			load()->func('communication');
			$res = ihttp_post($url,$postdata);
			$code = json_decode($res['content'],true);
			return $code;		
		}
		public function bookmsg($openid,$templateid,$page,$formid,$uname,$servicename,$booktime,$orderid,$address,$token){
			load()->func('communication');
			$url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$token;
			$postdata = '{
			  "touser": "'.$openid.'",  
			  "template_id": "'.$templateid.'", 
			  "page": "'.$page.'",          
			  "form_id": "'.$formid.'",         
			  "data": {
			      "keyword1": {
			          "value": "'.$uname.'", 
			          "color": "#173177"
			      }, 
			      "keyword2": {
			          "value": "'.$servicename.'", 
			          "color": "#173177"
			      }, 
			      "keyword3": {
			          "value": "'.$booktime.'", 
			          "color": "#173177"
			      } , 
			      "keyword4": {
			          "value": "'.$orderid.'", 
			          "color": "#173177"
			      } , 
			      "keyword5": {
			          "value": "'.$address.'", 
			          "color": "#173177"
			      },
			      "keyword6": {
			          "value": "您的预约号码为 '.$orderid.' 请在 '.$booktime.' 之前到达本店。", 
			          "color": "#173177"
			      } 		        
			  }
			}'; 
			$res = ihttp_post($url,$postdata);
			$code = json_decode($res['content'],true);
			return $code;
		}

		//短信消息

	public function sendmsg($sms_config,$details){
		include (MODULE_ROOT.'/public/dayu/TopSdk.php');	
		$d = json_decode($details,true);
		$name = $d['uname'];
		$sname = $d['goodsname'];
		$time = date('Y/m/d H:i',$d['starttime']).'-'.date('H:i',$d['endtime']);
		$phone = $d['phone'];
		$sms_note = $sms_config['sms_note'];
		$sms_conf = @json_decode($sms_config['sms_config'],true);
		$admin_phone = @json_decode($sms_config['admin_phone'],true);
		$DIE = count($admin_phone);
		if($sms_note=='1'&& is_array($admin_phone) && is_array($sms_conf)){
			$c = new TopClient;
			$c->appkey = $sms_conf['alikey'];
			$c->secretKey = $sms_conf['alisecret'];
			$req = new AlibabaAliqinFcSmsNumSendRequest;
			foreach ($admin_phone as $key => $p) {
				$req->setExtend("123456");
				$req->setSmsType("normal");
				$req->setSmsFreeSignName($sms_conf['signName']);
				$req->setSmsParam("{\"name\":\"$name\",\"sname\":\"$sname\",\"time\":\"$time\",\"phone\":\"$phone\"}");
				$req->setRecNum($p);
				$req->setSmsTemplateCode($sms_conf['template_id']);
				$resp = $c->execute($req);
				if($key+1==$DIE){
					break;
				}
			}
		}else{
			return false;
		}

	}

	public function sendSms($sms_config,$details){		
			include (MODULE_ROOT.'/public/dysms/SignatureHelper.php');
		    $params = array ();
		    $paramsData = array();
		    // *** 需用户填写部分 ***
		    $d = json_decode($details,true);
			$name = $d['uname'];
			$sname = $d['goodsname'];
			$time = date('Y-m-d H:i',$d['starttime']);
			$phone = $d['phone'];
			$paramsData = array("name"=>"{$name}","sname"=>"{$sname}","time"=>"{$time}","phone"=>"{$phone}");
			$sms_note = $sms_config['sms_note'];
			$sms_conf = @json_decode($sms_config['sms_config'],true);
			$admin_phone = @json_decode($sms_config['admin_phone'],true);
			$DIE = count($admin_phone);
		    // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
		    if($sms_note=='1'&& is_array($admin_phone) && is_array($sms_conf)){
			    $accessKeyId = $sms_conf['alikey'];
			    $accessKeySecret = $sms_conf['alisecret'];
			    // fixme 必填: 短信接收号码
			    $params["PhoneNumbers"] = "";
			    // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
			    $params["SignName"] = $sms_conf['signName'];
			    // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
			    $params["TemplateCode"] = $sms_conf['template_id'];
			    // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
			    $params['TemplateParam'] = $paramsData;
			    // fixme 可选: 设置发送短信流水号
			    $params['OutId'] = "12345";
			    $params['SmsUpExtendCode'] = "1234567";
			    // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
			    if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
			        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
			    }
			    foreach ($admin_phone as $key => $p) {
			    	$params["PhoneNumbers"] = $p;
				    // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
				    // 此处可能会抛出异常，注意catch
				    $sendSmsmsg = new SignatureHelper();
				    $content = $sendSmsmsg->request(
				        $accessKeyId,
				        $accessKeySecret,
				        "dysmsapi.aliyuncs.com",
				        array_merge($params, array(
				            "RegionId" => "cn-hangzhou",
				            "Action" => "SendSms",
				            "Version" => "2017-05-25",
				        ))
				    );
					if($key+1==$DIE){
						break;
					}			    
				}
			    return $content;	
		    }	
		}			

	}


?>